<template>
    <div class="e-form">
        <BillTop @cancel="printHandel"></BillTop>
        <div class="tabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="结算清单" name="qingdan" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="工程材料理论量" name="lilunliang" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="材料理论/实际消耗" name="xiaohao" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="终期结算协议书" name="xieyishu" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="项目结算台账汇总表" name="huizong" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%;" class="form">
                            <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="240px">
                              <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="结算编号：">
                                                {{ formData.billNo }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="期数：">
                                                {{ formData.period }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="合同名称："
                                                prop="contractName"
                                            >
                                                <el-input
                                                    style="flex: 1"
                                                    placeholder="选择合同"
                                                    v-model="
                                                        formData.contractName
                                                    "
                                                    disabled
                                                >
                                                    <i
                                                        slot="suffix"
                                                        class="
                                                            el-icon-document-copy
                                                        "
                                                        @click="
                                                            onSelectHetong
                                                        "
                                                    ></i>
                                                </el-input>
                                                <span
                                                    class="goTo"
                                                    @click="
                                                        goToContract(
                                                            formData.contractId
                                                        )
                                                    "
                                                    v-if="formData.contractId"
                                                    >查看合同</span
                                                >
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="外包方：">
                                                {{ formData.outsourcerName }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="结算日期："
                                                v-model="formData.settlementDate"
                                                value-format="yyyy-MM-dd"
                                                prop="settlementDate"
                                            >
                                                <el-date-picker
                                                    v-model="
                                                        formData.settlementDate
                                                    "
                                                    type="date"
                                                    placeholder="选择日期"
                                                >
                                                </el-date-picker>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="冲产业工人工资："
                                                prop="writeOffWages"
                                            >
                                               <el-input
                                                    v-model="formData.writeOffWages"
                                                    type="number"
                                                    @change="writeOffWagesEvent"
                                                >
                                                </el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="本期结算金额(不含保证金)："
                                                prop="excludingDepositAmount"
                                            >
                                                {{ currentAmountNoBond }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="保证金合计：">
                                                {{ bondTotal }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="税率%：">
                                                {{ formData.taxRate || 0 }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="本期结算金额(含保证金)："
                                            >
                                                {{
                                                    currentAmountNoBond + bondTotal
                                                }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="税额(元)："
                                            >
                                              <span v-if="!acceptanceData.length">
                                                     请先引入清单
                                                </span>
                                                <el-input
                                                    v-model="formData.taxAmount"
                                                    @change="taxAmountEvent"
                                                    type="number"
                                                    placeholder="请填写税额"
                                                    v-else
                                                >
                                                </el-input>
                                            </el-form-item>
                                        </el-col>

                                        <el-col :span="12">
                                            <el-form-item
                                                label="本期结算金额(含税)："
                                            >
                                                {{ currentAmountHaveTax }}
                                                <el-tooltip
                                                    content="本期结算金额（含税）=本期结算金额（不含保证金）+税额"
                                                    placement="top"
                                                >
                                                    <i
                                                        class="
                                                            el-icon-warning-outline
                                                            greenFont
                                                        "
                                                    ></i>
                                                </el-tooltip>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="状态：">
                                                {{ stateLable(formData.state) }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="传财务共享：">
                                                <span :class="isFontColor ? 'redFont' : 'greenFont'">{{shareLable(formData.easId)}}</span>
                                                <el-tooltip
                                                    content="预计xxx时间传输财务"
                                                    placement="top"
                                                >
                                                    <i
                                                        class="
                                                            el-icon-warning-outline
                                                            greenFont
                                                        "
                                                    ></i>
                                                </el-tooltip>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="币种：">
                                                {{ formData.currency }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="本位币：">
                                                {{ formData.baseCurName }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="本位币汇率："
                                            prop="baseCurRate">
                                                <el-input
                                                    v-model="
                                                        formData.baseCurRate
                                                    "
                                                    type="number"
                                                    @change="baseCurRateEvent"
                                                    v-if='isReviseBaseCurRate'
                                                >
                                                </el-input>
                                                <span v-else>
                                                    {{formData.baseCurRate}}
                                                </span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="人民币汇率：">
                                                {{ formData.rmbRate }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="录入机构：">
                                                {{ formData.orgName }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="录入日期：">
                                                {{ formData.gmtCreate }}
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24">
                                            <el-form-item
                                                label="本期结算内容概要："
                                            >
                                                <el-input
                                                    placeholder=""
                                                    v-model="formData.remarks"
                                                    class="input-with-select"
                                                    type="textarea"
                                                    :rows="3"
                                                    maxlength='500'
                                                >
                                                    <span>
                                                        {{ formData.remarks }}
                                                    </span>
                                                </el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                            </el-form>
                        </div>
                    </div>
                    <div id="qingdanCon" class="con">
            <div>
            <div class="e-table" style="background-color: #fff">
                <!-- 结算清单 -->
                <div id="changeDetailCon" class="con">
                            <div class="tabs-title" id="qingdan">
                                结算清单
                            </div>
                        </div>
                        <div class="errMessageBox">
                                <p class="errMessage" v-for="(item,index) in settlementErrorList" :key='index'>
                                    {{item}}
                                </p>
                </div>
                  <div class="bigBox">
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button
                                            size="small"
                                            class="btn-greenYellow"
                                            @click="
                                                settleOrgChange(
                                                    formData.contractId
                                                )
                                            "
                                        >
                                            引入清单</el-button
                                        >
                                        <span class="label"
                                            >查看清单范围：</span
                                        >
                                        <el-radio-group v-model="qingdanRange" @change="selectionList">
                                            <el-radio label="1"
                                                >本期结算清单</el-radio
                                            >
                                            <el-radio label="all"
                                                >全部清单</el-radio
                                            >
                                        </el-radio-group>
                                        <span class="label" v-if="formData.contractTypeValue == '1'"
                                            >查看清单维度：</span
                                        >
                                        <el-radio-group v-model="structure" v-if="formData.contractTypeValue == '1'">
                                            <el-radio label="1"
                                                >细目—>结构部位</el-radio
                                            >
                                            <el-radio label="2"
                                                >结构部位—>细目</el-radio
                                            >
                                        </el-radio-group>
                                        <span class="label">期数：</span>
                                        <div style="flex: 1">
                                            <el-select
                                                multiple
                                                v-model="qishu"
                                                collapse-tags
                                                placeholder="请选择"
                                                @change="onSelectQishu"
                                            >
                                                <el-option
                                                    v-for="item in qishuOptions"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                ></el-option>
                                            </el-select>
                                        </div>
                                    </div>
                                </div>
                                <div class="right">
                                    <div>
                                <!--@click="searchTableData" -->
                                        <el-input
                                            placeholder="请输入细目编号、细目名称或结构部位进行搜索"
                                            size="small"
                                            v-model="searchVal"
                                        >
                                            <img
                                                src="@/assets/search.png"
                                                slot="suffix"
                                            />
                                        </el-input>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- {{webData}} -->
                        <!-- 表格 -->
                        <div class="e-table e-tree-table">
                            <!-- default-expand-all 默认展开全部 -->
                            <el-table
                                :data="acceptanceData"
                                border
                                ref="acceptanceDataTable"
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                lazy
                                :load="onload"
                                row-key="uuid"
                                class="table"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{'tableData': acceptanceData, '_this': this, 'ref': 'acceptanceDataTable'}"
                            >
                                <el-table-column  fixed label="操作" width="150">
                                    <template slot-scope="{ row }">
                                         <span>{{row.serialNumber}}</span>
                                        <div class="handle"  v-if='isOnDelete(row)'>
                                            <img src="@/assets/btn/delete.png"  @click="handleDeletePlanList(row)">
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="itemNo"
                                    label="细目编号"
                                    fixed
                                    min-width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="itemName"
                                    label="细目名称"
                                    fixed
                                    min-width="150"
                                >
                                <template slot-scope="{row}">
                                    <span
                                        @click="examine(row)"
                                        style="color: blue; cursor: pointer"
                                        v-if="row.isBillLevel == 1"
                                    >
                                        {{ row.itemName }}
                                    </span>
                                    <span v-else>
                                        {{row.itemName}}
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="structureName"
                                    label="结构部位"
                                    min-width="150"
                                >
                                 <template slot-scope="{row}">
                                    <span v-if='row.type=="1"||row.type=="2"'>
                                         {{row.structureName}}
                                    </span>
                                    <span v-else>
                                       --
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="单位"
                                    min-width="150"
                                >
                                <template slot-scope="{row}">
                                    <span v-if='row.type=="1"||row.type=="2"'>
                                         {{row.unit}}
                                    </span>
                                    <span v-else>
                                       --
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="contractQuantity"
                                    label="合同数量"
                                    min-width="150"
                                >
                                <template slot-scope="{row}">
                                    <span v-if='row.type!="3"'>
                                         {{row.contractQuantity}}
                                    </span>
                                    <span v-else>
                                       --
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    label="合同单价"
                                    min-width="150"
                                    prop="contractPrice"
                                >
                                <template slot-scope="{row}">
                                    <span v-if='row.type=="1"||row.type=="2"'>
                                         {{row.contractPrice}}
                                    </span>
                                    <span v-else>
                                       --
                                    </span>
                                </template>
                                </el-table-column>
                                 <el-table-column
                                    label="合同金额"
                                    min-width="150"
                                    prop="contractAmount"
                                >
                                 <template slot-scope="{row}">
                                    <span v-if='row.type !="3"'>
                                         {{row.contractAmount}}
                                    </span>
                                    <span v-else>
                                       --
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    label="本期结算数量"
                                    min-width="200"
                                    prop="settlementQuantity"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input
                                            v-model="row.settlementQuantity"
                                            placeholder="请输入本期结算数量"
                                            v-if="row.isDetailed=='1'&&row.type=='1'&&row.unit!='总额'"
                                            v-enterFloat2Neg="{
                                                set: row,
                                                key:'settlementQuantity'
                                            }"
                                            @change="setQuantity(row)"
                                        ></el-input>
                                        <span v-else-if="row.type==2||row.type==4">
                                          {{treeUpSummary(row,'settlementQuantity',4)}}%
                                        </span>
                                          <span v-else-if="row.type==1">
                                          {{treeUpSummary(row,'settlementQuantity',4)}}
                                        </span>
                                        <span v-else>--</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="本期结算金额(元)"
                                    min-width="150"
                                    prop="settlementAmount"
                                >
                                <template slot-scope="{ row }">
                                         <el-input
                                            v-model="row.settlementAmount"
                                            placeholder="请输入本期结算金额"
                                            v-if="row.isDetailed=='1'&&[1,2,4].includes(row.type)&&(row.type==1?row.unit == '总额':true)"
                                            @change="setAmount(row)"
                                             v-enterFloatNeg="{
                                                set: row,
                                                key: 'settlementAmount'
                                            }"
                                        ></el-input>
                                        <span v-else>
                                            {{treeUpSummary(row,'settlementAmount')}}
                                        </span>
                                    </template>
                                </el-table-column>
                                <!-- 第一期到第x期不包含本期数量 -->
                                <el-table-column
                                    v-for="item in dynamicLoadingLable"
                                    :label="item.label"
                                    min-width="150"
                                    :prop="item.prop"
                                    :key="item.id"
                                >
                                </el-table-column>

                                <el-table-column
                                    label="截止上期末累计结算数量"
                                    min-width="200"
                                    prop="prevTotalQuantity"
                                >
                                <template slot-scope="{ row }">
                                 <span v-if="row.type==2||row.type==4">
                                    {{treeUpSummary(row,'prevTotalQuantity',4)}}%
                                </span>
                                 <span v-else-if="row.type==1">
                                    {{treeUpSummary(row,'prevTotalQuantity',4)}}
                                </span>
                                <span v-else>--</span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    label="截止上期末累计结算金额"
                                    min-width="200"
                                    prop="prevTotalAmount"
                                >
                                <template slot-scope="{ row }">
                                     {{treeUpSummary(row,'prevTotalAmount')}}
                                </template>
                                </el-table-column>

                                <el-table-column
                                    label="截止本期末累计结算数量"
                                    min-width="200"
                                    prop="currentTotalSettlementQuantity"
                                >
                                <template slot-scope="{ row }">
                                <span v-if="row.type==2||row.type==4">
                                    {{treeUpSummary(row,'currentTotalSettlementQuantity',4)}}%
                                </span>
                                 <span v-else-if="row.type==1">
                                    {{treeUpSummary(row,'currentTotalSettlementQuantity',4)}}
                                </span>
                                <span v-else>--</span>
                                </template>
                                </el-table-column>

                                <el-table-column
                                    label="截止本期末累计结算金额"
                                    min-width="200"
                                    prop="currentTotalSettlementAmount"
                                >
                                 <template slot-scope="{ row }">
                                     {{treeUpSummary(row,'currentTotalSettlementAmount')}}
                                </template>
                                </el-table-column>
                            </el-table>
                        </div>
            </div>
        </div>
                    </div>
                    <div id="lilunliangCon" class="con">
                        <div class="tabs-title" id="lilunliang">工程材料理论量</div>
                        <lilunliang />
                    </div>
                    <div id="xiaohaoCon" class="con">
                        <div class="tabs-title" id="xiaohao">材料理论/实际消耗</div>
                        <xiaohao />
                    </div>
                    <div id="xieyishuCon" class="con">
                        <div class="tabs-title" id="xieyishu">终期结算协议书</div>
                        <div style='height: 800px'>
                            <iframe id="iframe" :src="formData.agreementDocumentAddress" style="width: 100%; height: 99%" frameborder="0"></iframe>
                        </div>
                    </div>
                    <div id="huizong">
                         <div class="tabs-title" id="closingAccountTable">项目结算台账汇总表</div>
                        <ClosingAccountTable />
                    </div>
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="billId" bucketName="gongchengjieshuan" />
                    </div>
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <ComExaHistory :billType="billType" @getAuditHistory="getAuditHistory" :tableData="auditHistoryData" ref="ComExaHistory" />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" @exas="exas" :founderId="formData.founderId" :state="formData.state"/>
            <el-button type="primary" @click="onReload">重新汇总</el-button>
            <el-button @click="onCancel">取消</el-button>
        </div>
    </div>
</template>

<script>
import { openAppClient, selectDataClient, throttle, hideLoading, getUuid } from '@/utils/common'
// eslint-disable-next-line no-unused-vars
import { getBaseInfo, getDetail, delBill, modifyBaseInfo, modifyDetail, reSummary } from '@/api/settlementManagement/gongchengjieshuan/guochengjieshuan'
// eslint-disable-next-line no-unused-vars
import { getAuditHistoryLs, flowCommit, flowAudit, getCurrentState, flowUndoAudit, flownullify
} from '@/api/settlementManagement/gongchengjieshuan/jiakoukuan'
import AttachComp from '@/components/common/attachIndex'
//审核历史
import ComExaHistory from '@/components/common/exaHistory.vue'
import ComExaButtons from '@/components/common/exaButtons'
import Lilunliang from './components/lilunliang'
import Xiaohao from './components/xiaohao'
import ClosingAccountTable from './components/closingAccountTable'
import { mapState, mapMutations } from 'vuex'
import '@/utils/jquery.scrollTo.min'
import httpRequest from '@/api/settlementManagement/gongchengjieshuan/gongchengAndzhongqi'
import axios from 'axios'
import store from '@/store'
let oldRouter = {} // 上一个页面来源
export default {
    components: {
        AttachComp,
        ComExaHistory,
        ComExaButtons,
        Lilunliang,
        Xiaohao,
        ClosingAccountTable
    },
    data () {
        return {
            tabsName: 'baseInfo',
            billType: '1098',
            billId: this.$route.query.billid,
            flowParams: {
                'billId': '',
                'billType': '',
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            //表单数据
            formData: {},
            tableDataQd: [],
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            val: '', //冲预付款金额（元）
            auditHistoryData: [],
            auditState: {},
            rules: {
                contractName: [{ required: true, message: '请选择合同', trigger: 'change' }],
                settlementDate: [{ required: true, message: '请选择结算日期', trigger: 'change' }],
                baseCurRate: [{ required: true, message: '本位币汇率不能为空', trigger: ['blur', 'change'] }],
            },
            //获取当前页面可以操作的按钮
            buttonParams: {
                billId: this.$route.query.billid,
                billType: '1098', // 对应模块Id
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            //提交审核参数
            auditParams: {
                billId: this.$route.query.billid,
                billType: '1098',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false,
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            winEvent: {},
            isReviseBaseCurRate: true, //本位币汇率是否可以修改
            //结算清单明细
            acceptanceData: [],
            //工程内容
            projectContent: {
                serialNumber: 1,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '合同工程内容', //细目名称 扩大基础"
                type: 1, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '1', //每个父级的id
            },
            //预付款
            advanceCharge: {
                serialNumber: 2,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '分包预付款', //细目名称 扩大基础"
                type: 2, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '2', //每个父级的id
            },
            //加扣款
            plusDeduction: {
                serialNumber: 3,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '加扣款', //细目名称 扩大基础"
                type: 3, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '3', //每个父级的id
            },
            //税金
            taxes: {
                serialNumber: 4,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '税金', //细目名称 扩大基础"
                type: 5, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '4', //每个父级的id
            },
            //保证金
            bond: {
                serialNumber: 5,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '保证金', //细目名称 扩大基础"
                type: 4, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '5', //每个父级的id
            },
            //不含税结算价合计
            noTaxesTotalSettlement: {
                itemName: '不含税结算价合计', //细目名称 扩大基础"
                uuid: getUuid(), //表格需要的id
                itemId: '6', //每个父级的id
            },
            //含税结算价合计
            taxesTotalSettlement: {
                itemName: '含税结算价合计', //细目名称 扩大基础"
                uuid: getUuid(), //表格需要的id
                itemId: '7', //每个父级的id
            },
            //结算合计
            totalSettlement: {
                itemName: '结算合计', //细目名称 扩大基础"
                uuid: getUuid(), //表格需要的id
                itemId: '8', //每个父级的id
            },
            stageNumberTableList: [], //数量期数表格数据
            stageAmountTableList: [], //金额期数表格数据
            qingdanRange: 'all', //清单类型选择
            structure: '1',
            qishuOptions: [], //所有期数
            qishu: [], //期数vauel数组
            oldQishu: [], //保存修改之前的老数据
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            settlementErrorList: [], //结算明细中用于提示错误的数据
            tabArr: [], //用于验证功能列表中的必填项
            isFontColor: true, //传输财务共享颜色未传，返回修改 红色 财务共享审核中，已传 绿色
            secondParty: {}, //外包方信息
            searchVal: '', //表格搜索内容
            webData: '', //页面测试数据
        }
    },
    watch: {
    //监听累计结算金额（不含保证金）
        currentAmountNoBond: {
            deep: true,
            handler (newVal, oldVal) {
                if(newVal == oldVal) {
                    return
                }
                this.formData.taxAmount = (newVal * this.formData.taxRate / 100).toFixed(2) * 1
                this.taxes.settlementAmount = this.formData.taxAmount || 0
                this.taxes.currentTotalSettlementAmount = ((Number(this.formData.taxAmount) || 0) +
                (Number(this.taxes.prevTotalAmount) || 0)).toFixed(2) * 1
            }
        },
        //监听合同工程内容更新不含税结算价合计
        projectContent: {
            deep: true,
            handler (newVal) {
                this.setTotalSettlement([this.plusDeduction, this.advanceCharge, newVal], this.noTaxesTotalSettlement)
                this.setTotalSettlement([this.plusDeduction, this.advanceCharge, this.taxes, newVal], this.taxesTotalSettlement)
                this.setTotalSettlement([this.plusDeduction, this.advanceCharge, this.taxes, this.bond, newVal], this.totalSettlement)
            }
        },
        //监听分包预付款更新不含税结算价合计
        advanceCharge: {
            deep: true,
            handler (newVal) {
                this.setTotalSettlement([this.plusDeduction, newVal, this.projectContent], this.noTaxesTotalSettlement)
                this.setTotalSettlement([this.plusDeduction, newVal, this.taxes, this.projectContent], this.taxesTotalSettlement)
                this.setTotalSettlement([this.plusDeduction, newVal, this.taxes, this.bond, this.projectContent], this.totalSettlement)
            }
        },
        //监听加扣款更新
        plusDeduction: {
            deep: true,
            handler (newVal) {
                this.setTotalSettlement([newVal, this.advanceCharge, this.projectContent], this.noTaxesTotalSettlement)
                this.setTotalSettlement([newVal, this.advanceCharge, this.taxes, this.projectContent], this.taxesTotalSettlement)
                this.setTotalSettlement([newVal, this.advanceCharge, this.taxes, this.bond, this.projectContent], this.totalSettlement)
            }
        },
        //监听税金更新含税结算价合计
        taxes: {
            deep: true,
            handler (newVal) {
                this.setTotalSettlement([this.projectContent, this.plusDeduction, this.advanceCharge, newVal], this.taxesTotalSettlement)
                this.setTotalSettlement([this.projectContent, this.plusDeduction, this.advanceCharge, newVal], this.totalSettlement)
            }
        },
        //监听保证金更新结算合计
        bond: {
            deep: true,
            handler (newVal) {
                this.setTotalSettlement([this.projectContent, this.plusDeduction, this.advanceCharge, this.taxes, newVal], this.totalSettlement)
            }
        }
    },
    created () {
        this.flowParams.billId = this.billId
        this.flowParams.billType = this.billType
    },
    mounted () {
        this.init()
        this.$set(this.auditState, 'canAudit', true)
        // 如果是新增保存后点击“继续”跳转过来的，则定位到第2个tab
        if (oldRouter.path === '/guochengFinalJieshuanAdd') {
            this.tabsName = 'baseInfo'
            this.$nextTick(() => {
                this.onChangeTab({ name: 'baseInfo' })
            })
        }
        this.auditState = this.$route.params.auditState
        if (!this.auditState) {
            this.getCurrentUnitInfo()
        }
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'qingdan', 'lilunliang', 'xiaohao', 'xieyishu', 'huizong', 'attach', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    beforeRouteEnter (to, from, next) {
        oldRouter = from
        next()
    },
    beforeRouteLeave (to, from, next) {
        oldRouter = null
        next()
    },
    computed: {
        ...mapState('equip', ['equipData']),
        ...mapState({
            currencyForm: state => state.equip.equipData.currencyForm//币种
        }),
        //根据状态值参数决定是否展示打印按钮
        stateLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)
                return obj ? obj.label : ''
            }
        },
        //传输财务共享
        shareLable () {
            return param => {
                const state = this.$store.state.equip.equipData.shareFrom
                const obj = state.find(x => x.value == param)
                if(obj) {
                    if(obj.label == '未传' || obj.label == '返回修改') {
                        this.isFontColor = true
                    }else {
                        this.isFontColor = false
                    }
                }
                return obj ? obj.label : ''
            }
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 85 - this.lastConHeight
        },
        //本期结算金额不含保证金
        currentAmountNoBond () {
            let total = 0
            this.acceptanceData.forEach(item=>{
                if(item.type == 1 || item.type == 2 || item.type == 3) {
                    total += Number(item.settlementAmount)
                }
            })
            return (total || 0).toFixed(2) * 1
        },
        //保证金合计
        bondTotal () {
            let target = 0
            this.acceptanceData.forEach(item=>{
                if(item.type == 4) {
                    target = Number(item.settlementAmount)
                }
            })
            return target
        },
        //本期结算金额含税
        currentAmountHaveTax () {
            return ((Number(this.formData.taxAmount) || 0) + (Number(this.currentAmountNoBond) || 0)).toFixed(2) * 1
        },
        //根据选中期数动态展示表格
        dynamicLoadingLable () {
            const list =  []
            this.qishu.forEach(item=>{
                if(item) {
                    const obj1 = {
                        label: `第${item}期结算金额`,
                        prop: `settlementAmount${item}`,
                        id: getUuid()
                    }
                    const obj2 = {
                        label: `第${item}期结算数量`,
                        prop: `settlementQuantity${item}`,
                        id: getUuid()
                    }
                    list.push(obj1, obj2)
                }
            })
            return list
        },
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        //加法运算并保留任意位小数
        summationResToOrFourDecimal (a, b, decimal = 2) {
            return ((Number(a) || 0) + (Number(b) || 0)).toFixed(decimal) * 1
        },
        //初始化表格数据
        initTableData () {
            //工程内容
            this.projectContent = {
                serialNumber: 1,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '合同工程内容', //细目名称 扩大基础"
                type: 1, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '1', //每个父级的id
            }
            //预付款
            this.advanceCharge = {
                serialNumber: 2,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '分包预付款', //细目名称 扩大基础"
                type: 2, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '2', //每个父级的id
            }
            //加扣款
            this.plusDeduction = {
                serialNumber: 3,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '加扣款', //细目名称 扩大基础"
                type: 3, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '2', //每个父级的id
            }
            //税金
            this.taxes = {
                serialNumber: 4,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '税金', //细目名称 扩大基础"
                type: 5, //结算清单类型(1:清单;3:加扣款;4:保证金;5:税金)
                uuid: getUuid(), //表格需要的id
                itemId: '3', //每个父级的id
            }
            //保证金
            this.bond = {
                serialNumber: 5,
                children: [], //子集数组
                settlementAmount: 0, //本期结算金额
                prevTotalAmount: 0, //截止上期末累计结算金额
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                itemName: '保证金', //细目名称 扩大基础"
                type: 4, //结算清单类型(1:清单;3:加扣款;4:保证金)
                uuid: getUuid(), //表格需要的id
                itemId: '4', //每个父级的id
            }
            //不含税结算价合计
            this.noTaxesTotalSettlement = {
                itemName: '不含税结算价合计', //细目名称 扩大基础"
                uuid: getUuid(), //表格需要的id
                itemId: '5', //每个父级的id
            }
            //含税结算价合计
            this.taxesTotalSettlement = {
                itemName: '含税结算价合计', //细目名称 扩大基础"
                uuid: getUuid(), //表格需要的id
                itemId: '6', //每个父级的id
            }
            //结算合计
            this.totalSettlement = {
                itemName: '结算合计', //细目名称 扩大基础"
                uuid: getUuid(), //表格需要的id
                itemId: '7', //每个父级的id
            }
        },
        //树向上汇总row为当前数据,key为需要计算的属性
        treeUpSummary (row, key, index = 2) {
            if(row.children && row.children.length > 0 ) {
                row[key] = row.children.reduce((count, item)=>count + (parseFloat(item[key]) || 0), 0).toFixed(index) * 1
                row[key] = row[key] || 0
            }
            return row[key]
        },
        //设置本期之前的所有期数
        setHistoryPeriods (peridos) {
            const periodsList = [{ label: '全部', value: 0 }] //第一条数据默认全部
            for (let i = 1; i <= peridos; i++) {
                const obj = {
                    label: `第${i}期`,
                    value: i
                }
                periodsList.push(obj)
            }
            const valueList = periodsList.map(item => item.value)
            this.qishuOptions = periodsList
            this.qishu = valueList
            this.oldQishu = valueList
        },
        //设置历史期数
        setTableHistoryPeriods (obj, list) {
            let max = 0 // 最大期数
            let totalAmount = 0 //累计金额
            let totalQuantity = 0 // 累计数量
            //税金参数（税金与其他的结算类型一起返回需要单独找出税金）
            let taxesMax = 0
            let taxesTotalAmount = 0
            const taxeObj = {}
            list.forEach(item=>{
                //税金type等于5没有就是目标
                if(item.type == 5) {
                    const p = item.period
                    taxeObj['settlementAmount' + p] = item.settlementAmount || 0
                    taxesTotalAmount += Number(item.settlementAmount)
                    taxesMax = Math.max(taxesMax, p)
                }else {
                    const p = item.period
                    obj['settlementAmount' + p] = item.settlementAmount || 0
                    obj['settlementQuantity' + p] = item.settlementQuantity || 0
                    totalAmount += Number(item.settlementAmount)
                    totalQuantity += Number(item.settlementQuantity)
                    max = Math.max(max, p)
                }
            })
            totalAmount = totalAmount.toFixed(2) * 1
            totalQuantity = totalQuantity.toFixed(4) * 1
            taxesTotalAmount = taxesTotalAmount.toFixed(2) * 1
            const arr = [
                { type: 'target', max, totalAmount, totalQuantity, other: {} },
                { type: 'taxes', max: taxesMax, totalAmount: taxesTotalAmount, totalQuantity: '', other: taxeObj
                }]
            return arr
        },
        //重新赋值并保留两位小数
        setDataRetainTwoDecimal (list, dtlId, key, val, decimal = 2) {
            const length = list.length
            for (let i = 0; i < length; i++) {
                if (list[i].dtlId == dtlId) {
                    list[i][key] = Number(val).toFixed(decimal) * 1
                    break
                }
            }
        },
        //总税额验证
        taxAmountEvent (val) {
            const target = ((val * 1).toFixed(2) * 1) || 0
            this.formData.taxAmount = target
            this.taxes.settlementAmount = target
            this.taxes.currentTotalSettlementAmount = ((Number(this.taxes.prevTotalAmount) || 0) + target).toFixed(2) * 1
        },
        //本位币汇率事件
        baseCurRateEvent (val) {
            if (val <= 0) {
                this.$message.error('本位币汇率必须大于0')
                this.formData.baseCurRate = 1
            } else {
                this.formData.baseCurRate = (val * 1).toFixed(4) * 1
            }
        },
        //工人工资事件
        writeOffWagesEvent (val) {
            this.formData.writeOffWages = val ? Number(val).toFixed(2) * 1 : 0
        },
        //处理明细参数并返回保存参数
        setParams (commit) {
            //处理明细参数
            let sendOutList = []
            this.settlementErrorList = []
            const clone = JSON.parse(JSON.stringify(this.acceptanceData))
            const cloneList = clone.filter(item=>[1, 2, 3, 4].includes(item.type))
            if(cloneList.length > 0) {
                cloneList.forEach(item=>{
                    const paramList = this.flatTree(item.children)
                    sendOutList = [...sendOutList, ...paramList]
                })
            }
            //处理清单数据
            if(sendOutList.length > 0) {
                sendOutList.forEach(item => {
                    item.billId = this.billId
                    item.settlementAmount = item.settlementAmount * 1
                    item.contractQuantity = item.contractQuantity * 1 || parseFloat(item.contractQuantity)
                    item.prevTotalQuantity = item.prevTotalQuantity * 1 || parseFloat(item.prevTotalQuantity)
                    item.settlementQuantity = item.settlementQuantity * 1 || parseFloat(item.settlementQuantity)
                    if(item.changeType != 1) {
                        item.changeType = 2
                    }
                })
            }
            // 处理基本信息中用计算属性计算的参数
            const obj = {
                excludingDepositAmount: this.currentAmountNoBond,
                totalBond: this.bondTotal,
                totalAmount: this.currentAmountHaveTax,
                includingDepositAmount: this.currentAmountNoBond + this.bondTotal,
                settlementType: 2,
                currentTotalAmount: ((Number(this.formData.previousTotalAmount) || 0) + (Number(this.totalSettlement.settlementAmount) || 0)).toFixed(2) * 1
            }
            if(sendOutList.length > 0) {
                //优先保存清单在保存基本信息，不然加扣款会有问题
                httpRequest.updeteProjectSettlementDetailed(sendOutList)
                    .then(()=>{
                        httpRequest.updateProjectSettlementInfo({
                            ...this.formData,
                            ...obj,
                        })
                            .then(()=>{
                                if(!commit) {
                                    this.clientPop('suc', '保存成功')
                                    location.reload()
                                }
                            })
                    })
            }else {
                httpRequest.updateProjectSettlementInfo({
                    ...this.formData,
                    ...obj,
                })
                    .then(()=>{
                        if(!commit) {
                            this.clientPop('suc', '保存成功')
                            location.reload()
                        }
                    })
            }
        },
        //验证基本信息
        verificationEssentialInformation () {
            const { contractName, settlementDate, baseCurRate } = this.formData
            const list = [contractName, settlementDate, baseCurRate]
            return list.some(item => String(item) == '' || item == null)
        },
        //验证本期结算金额(不含保证金)是否大于冲产业工人工资
        settlemntAmountIsWages () {
            return this.currentAmountNoBond < (this.formData.writeOffWages || 0)
        },
        //验证分包预付款截止本期末累计金额是否超合同金额(true不满足,false满足)
        returnAdvanceCharge () {
            let isTrue = false
            if(this.advanceCharge.children.length > 0) {
                this.advanceCharge.children.forEach(item=>{
                    if(item.currentTotalSettlementAmount > item.contractAmount) {
                        isTrue = true
                    }
                })
            }
            return isTrue
        },
        //验证保证金本期末结算金额是否超合同金额(true不满足,false满足)
        returnBondAmount () {
            let isTrue = false
            if(this.bond.children.length > 0) {
                this.bond.children && this.bond.children.forEach(item=>{
                    if(item.children && item.children.length > 0) {
                        isTrue = item.children.some(son=>(son.currentTotalSettlementAmount || 0) > (son.contractAmount || 0))
                    }
                })
            }
            return isTrue
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //保存按钮
        onSave () {
            this.setParams()
            // Promise.all(paramsList)
            //     .then(() => {
            //         this.clientPop('suc', '数据保存成功')
            //         location.reload()
            //     })
            //     .catch(() => {
            //         this.clientPop('err', '数据保存失败', () => {
            //             this.scorllError()
            //         })
            //     })
            //     .finally(() => {
            //         hideLoading()
            //     })
        },
        //保存并提交
        async submitCommit () {
            this.settlementErrorList = []
            // 验证基本信息
            if(this.verificationEssentialInformation()) {
                this.setError('baseInfo')
                this.scorllError()
                this.$message.error('合同、结算日期、本位币汇率不能为空')
                return
            }
            //验证本期结算金额(不含保证金)是否大于冲产业工人工资
            if(this.settlemntAmountIsWages()) {
                this.setError('baseInfo')
                this.scorllError()
                this.$message.error('本期结算金额(不含保证金)必须大于等于冲产业工人工资')
                return
            }
            // 验证明细中必须至少存在一种结算类型（预付款、加扣款等）
            if(this.thereIsAtLeastOne()) {
                this.settlementErrorList = ['请至少选择一种类型进行结算']
                this.setError('qingdan')
                this.scorllError()
                return
            }
            //验证必填项是否全是0
            if(this.isAreTheyAllZero()) {
                this.settlementErrorList = ['结算清单的本期结算金额至少有一个不能为0']
                this.setError('qingdan')
                this.scorllError()
                return
            }
            // 验证分包预付款截止本期末累计结算金额是否超合同金额
            if(this.returnAdvanceCharge()) {
                this.settlementErrorList = ['分包预付款的截止本期末累计结算金额不能超分包预付款的合同金额，请检查！']
                this.setError('qingdan')
                this.scorllError()
                return
            }
            //验证保证金本期末结算金额是否超保证金合同金额
            if(this.returnBondAmount ()) {
                this.settlementErrorList = ['扣/返还的截止本期末累计结算金额不能超保证金的合同金额，请检查！']
                this.setError('qingdan')
                this.scorllError()
                return
            }
            //验证外包是否合格
            if(await this.getSecondPartyData(this.formData.outsourcerId)) {
                return
            }
            this.setParams('commit')
            httpRequest.applicationReview(this.auditParams)
                .then(() => {
                    this.clientPop('suc', '保存并提交成功', () => {
                        this.printHandel()
                    })
                })
                .catch(() => {
                    this.clientPop('err', '提交失败！')
                })
        },
        // 底部删除按钮
        onDel () {
            this.clientPop('info', this.oneDeleteErr, async () => {
                await delBill({ id: this.billId })
                this.clientPop('suc', '删除成功', () => {
                    this.$router.replace('/guochengZqJieshuanList')
                })
            })
        },
        async onUndo () {
            try {
                await flowUndoAudit(this.flowParams)
                this.clientPop('suc', '撤回成功', () => {
                    this.$router.replace('/guochengZqJieshuanList')
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        onNullify () {
            try {
                openAppClient('/nullifyDialog', '填写作废说明', async () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    await flownullify({
                        'billId': this.billId,
                        'billType': this.billType,
                        'nullifyCreated': '',
                        'nullifyCreator': '',
                        'nullifyCreatorId': '',
                        'nullifyDescription': auditParams.nullifyDescription,
                        'nullifyReason': auditParams.nullifyReason
                    })
                    this.clientPop('suc', '伤废成功', () => {
                        this.$router.replace('/guochengZqJieshuanList')
                    })
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        //取消按钮
        onCancel () {
            if (oldRouter.path === '/guochengZqJieshuanList') {
                this.$router.back()
            } else {
                this.$router.replace('/guochengZqJieshuanList')
            }
        },
        //流程按钮
        exas (str) {
            switch (str) {
            case 'submit':
                this.onSave()
                break
            case 'submitCommit':
                this.submitCommit() //保存并提交
                break
            case 'deleteData':
                this.onDel()
                break
            case 'undoAudit':
                this.onUndo()
                break
            case 'nullify':
                this.onNullify()
            }
        },
        async getCurrentUnitInfo () {
            this.auditState = await getCurrentState(this.flowParams)
        },
        // 审核历史列表查询
        async getAuditHistory () {
            this.auditHistoryData = await getAuditHistoryLs(this.flowParams)
        },
        getState (state) {
            const findObj = this.equipData.state.find(item => item.value === Number(state))
            return findObj ? findObj.label : ''
        },
        //选择合同弹框
        onSelectHetong () {
            selectDataClient({
                SelectServiceToken: '/subcontract/thirdParty/getProjectForProcess', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: '2',    // 接口参数(name为模拟参数)
                Title: '选择分包合同' // 标题
            }).then(res => {
                // this.setSelectedInfo(res)
                // openAppClient('/showSelectedData', '选择结果')
                const val = res[0]
                this.formData.contractId = val.contractId
                this.formData.contractName = val.contractName
                this.formData.contractNo = val.contractNumber
                this.formData.outsourcerId = val.secondPartyId
                this.formData.outsourcerName = val.secondPartyName
                this.formData.taxRate = val.taxRate
                this.formData.currencyId = val.currencyId
                this.formData.currency = val.currencyName || this.currencyForm.filter(item=>item.value == val.currencyId)[0].label
                this.formData.baseCurId = val.baseCurId
                this.formData.baseCurName = val.baseCurName
                this.formData.rmbRate = val.rmbRate
                this.formData.nailDetailedListState = val.nailDetailedListState //是否有甲供清单
                this.isReviseBaseCurRate = !(this.formData.currency == this.formData.baseCurName)
                this.formData.baseCurRate = this.formData.currency == this.formData.baseCurName ? 1 : 0
                //查询接口期数
                httpRequest.getNextPeriod({ contractId: val.contractId })
                    .then(res=>{
                        this.formData.period = res
                    })
                //获取合同截止上期末累计结算金额
                httpRequest.getPreviousTotalAmount({ contractId: val.contractId })
                    .then(res=>{
                        if(typeof res == 'number') {
                            this.formData.previousTotalAmount = res
                        }else {
                            this.formData.previousTotalAmount = 0
                        }
                    })
                this.acceptanceData = []
                this.initTableData ()
                this.acceptanceData.push(this.projectContent, this.advanceCharge, this.plusDeduction, this.taxes, this.bond, this.noTaxesTotalSettlement, this.taxesTotalSettlement, this.totalSettlement)
            })
        },
        //重新汇总
        onReload () {
            if(this.formData.contractId) {
                this.gethuizongData(this.formData.contractId, this.formData.orgId, 1)
                this.$message({
                    showClose: true,
                    type: 'success',
                    message: '重新汇总成功'
                })
            }else {
                this.$message.error('请先选择合同')
            }
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                const lastCon = document.getElementById('auditHistoryCon')
                if (lastCon) {
                    const lastConHeight = lastCon.offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //前往合同页面进行查看
        goToContract (contractId) {
            openAppClient(
                `/contractDefinitionShow?billid=${contractId}&isview=true`, '查看分包合同'
            )
        },
        //结算金额事件
        setAmount (row) {
            row.settlementAmount = Number(row.settlementAmount).toFixed(2) * 1
            //合同清单
            if(row.type == 1) {
                row.currentTotalSettlementAmount = ((Number(row.prevTotalAmount) || 0 ) + (Number(row.settlementAmount) || 0)).toFixed(2) * 1
            }
            //预付款
            if(row.type == 2) {
                row.currentTotalSettlementAmount = ((Number(row.prevTotalAmount) || 0 ) + (Number(row.settlementAmount) || 0)).toFixed(2) * 1
                //本期数量
                if(row.settlementAmount && row.contractAmount) {
                    row.settlementQuantity = (row.settlementAmount / row.contractAmount * 100).toFixed(4) * 1
                }
                //截止本期末数量
                if(row.currentTotalSettlementAmount && row.contractAmount) {
                    const quantity = (row.currentTotalSettlementAmount / row.contractAmount * 100).toFixed(4) * 1
                    row.currentTotalSettlementQuantity = quantity
                }
            }
            //保证金
            if(row.type == 4) {
                const contractAmount = row.contractAmount
                row.settlementAmount = row.marginType == 1 ? 0 - row.settlementAmount : row.settlementAmount
                row.currentTotalSettlementAmount = ((Number(row.prevTotalAmount) || 0 ) + (Number(row.settlementAmount) || 0)).toFixed(2) * 1
                row.settlementQuantity = contractAmount ? ((row.settlementAmount / contractAmount * 100).toFixed(4) * 1) : 0
                const quantity = (row.currentTotalSettlementAmount / contractAmount * 100).toFixed(4) * 1
                row.currentTotalSettlementQuantity = quantity
            }
        },
        //合同清单结算数量事件
        setQuantity (row) {
            if(row.type == 1) {
                //验证数量是否超当前施工最大数量
                if(row.settlementQuantity > row.projectLog ) {
                    row.settlementQuantity = row.projectLog
                    this.$message.error('本期结算数量不可超当前施工日志最大数量:' + row.projectLog)
                }
                row.settlementQuantity = Number(row.settlementQuantity).toFixed(4) * 1
                row.settlementAmount = parseInt((row.settlementQuantity * (row.contractPrice || 0)))
                row.currentTotalSettlementQuantity = ((Number(row.prevTotalQuantity) || 0) + (Number(row.settlementQuantity) || 0)).toFixed(4) * 1
                row.currentTotalSettlementAmount = ((Number(row.settlementAmount) || 0) + (Number(row.prevTotalAmount) || 0)).toFixed(4) * 1
            }
        },
        //切换清单事件
        selectionList (val) {
            let res = []
            if(val == 'all') {
                const list = []
                this.qishuOptions.forEach(item=>{
                    list.push(item.value)
                })
                res = list
            }
            this.qishu = res
        },
        //修改期数
        onSelectQishu (e) {
            let difference
            // 选中
            if (e.length > this.oldQishu.length) {
                difference = e.find(item => this.oldQishu.indexOf(item) === -1)
                // 选中 “全部”时
                if (difference === 0) {
                    this.qishu = this.qishuOptions.map(item => item.value)
                } else {
                    // 如果选中项数为 除了 “全部” 外的所有
                    if (e.length === this.qishuOptions.length - 1) {
                        this.qishu = this.qishuOptions.map(item => item.value)
                    }
                }
            } else {
                // 取消
                difference = this.oldQishu.find(item => e.indexOf(item) === -1)
                if (difference === 0) {
                    this.qishu = []
                } else {
                    // 如果取消之前是全部选中，则取消选中 “全部”
                    if (this.oldQishu.length === this.qishuOptions.length) {
                        this.qishu.splice(0, 1)
                    }
                }
            }
            this.oldQishu = this._.clone(this.qishu)
        },
        // elment表格事件
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        // elment表格事件
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        //初始化数据
        init () {
            Promise.all([
                this.getInfoData (),
                this.getInfoDetailed(),
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取基本信息数据
        getInfoData () {
            httpRequest.getProjectSettlementInfoData({ id: this.billId })
                .then(res=>{
                    //获取当前页面可以操作的按钮
                    // httpRequest.getButtons(this.buttonParams)
                    //     .then(butRes => {
                    //         if (res.state == 1) {
                    //             butRes.canAudit = false // 被打回的审核状态不存在审核和作废功能
                    //             butRes.canUndoAudit = false // 测回同理
                    //             this.deleteBut = 1 // 删除同理
                    //             this.isShowPrint = false // 打印同理
                    //         }
                    //         this.auditState = butRes
                    //     })
                    this.isReviseBaseCurRate = !(res.baseCurRate == 1)
                    this.formData = { ...res }
                    httpRequest.getNextPeriod({ contractId: res.contractId })
                        .then(data=>{
                            this.formData.period = data
                        })
                    //获取合同截止上期末累计结算金额
                    httpRequest.getPreviousTotalAmount({ contractId: res.contractId })
                        .then(data=>{
                            if(typeof data == 'number') {
                                this.formData.previousTotalAmount = data
                            }else {
                                this.formData.previousTotalAmount = 0
                            }
                        })
                    // 以下是关于终期协议书引入在线word文档的代码
                    if (!this.formData.agreementDocumentAddress) {
                        axios
                            .post('/node/generate', {
                                billId: this.billId,
                                token: localStorage.getItem('token'),
                                org: encodeURIComponent(JSON.stringify(store.state.userInfo.orgInfo)),
                                module: 'gczqjs' // 工程终期结算
                            })
                            .then(res => {
                                const data = JSON.parse(res.data.body)
                                const fileName = encodeURI(data.filename)
                                this.formData.agreementDocumentAddress = `http://192.168.100.100:1027/getFileUrl?fileName=${fileName}`
                            })
                    }
                })
        },
        //获取历史数据
        async getHistoryData (item) {
            const resLine = await httpRequest.getProjectSettlementHistory({
                'contractId': this.formData.contractId,
                'dtls': [
                    {
                        'marginType': item.marginType,
                        'sourceId': item.sourceId,
                        'structureId': item.structureId,
                        'type': item.type
                    }
                ],
                'orgId': this.formData.orgId,
                'period': this.formData.period || 1
            })
            return this.setTableHistoryPeriods(item, resLine)
        },
        //获取施工日志
        async getListCanSettleQuantity (item) {
            const resLine = await httpRequest.getListCanSettleQuantity({
                'contractId': this.formData.contractId,
                'dtls': [
                    {
                        'codeId': item.parentId,
                        'structureId': item.structureId,
                        'sumQty': 0
                    }
                ]
            })
            return resLine
        },
        //获取明细数据仅限父级
        getInfoDetailed () {
            httpRequest.getProjectSettlementDetailed({ billId: this.billId, parentId: '0' }).then( res=>{
                if(res.length > 0) {
                    res.forEach(item=>{
                        //获取预付款
                        if(item.isDetailed == 1) {
                            this.getHistoryData(item)
                                .then(r=>{
                                    let totalQuantity = 0
                                    let totalAmount = 0
                                    let max = 0
                                    r.forEach(o=>{
                                        //目标
                                        if(o.type == 'target') {
                                            totalQuantity = o.totalQuantity || 0
                                            totalAmount = o.totalAmount || 0
                                            max = o.max
                                            const currentTotalSettlementAmount = this.summationResToOrFourDecimal(totalAmount, item.settlementAmount)
                                            const currentTotalSettlementQuantity = this.summationResToOrFourDecimal(totalQuantity, item.settlementQuantity, 4)
                                            Object.assign(item, { prevTotalQuantity: totalQuantity, prevTotalAmount: totalAmount, currentTotalSettlementAmount, currentTotalSettlementQuantity })
                                            this.setHistoryPeriods(max)
                                        }else {
                                            const currentTotalSettlementAmount = this.summationResToOrFourDecimal(o.totalAmount, this.taxes.settlementAmount)
                                            //税金
                                            Object.assign(this.taxes, { prevTotalAmount: o.totalAmount, currentTotalSettlementAmount, ...o.other })
                                            this.setHistoryPeriods(o.max)
                                        }
                                    })
                                })
                        }
                        Object.assign(item, { children: [], hasChildren: [], uuid: getUuid() })
                    })
                    const projectContentList = res.filter(item=>item.type == 1)
                    const advanceChargeList = res.filter(item=>item.type == 2)
                    const plusDeductionList = res.filter(item=>item.type == 3)
                    const bondList = res.filter(item=>item.type == 4)
                    const plusDeductionTree =  this.listConversionTreeOther(plusDeductionList, '0', 0)
                    const advanceChargeTree = this.listConversionTreeOther(advanceChargeList, '0', 0)
                    const bondTree =  this.listConversionTreeOther(bondList, '0', 0)
                    this.projectContent.children = projectContentList
                    this.advanceCharge.children = advanceChargeTree
                    this.plusDeduction.children = plusDeductionTree
                    this.bond.children = bondTree
                    this.taxes.settlementAmount = this.formData.taxAmount || 0
                    this.taxes.currentTotalSettlementAmount = ((Number(this.formData.taxAmount) || 0) + ( Number(this.taxes.prevTotalAmount) || 0)).toFixed(2) * 1
                    this.acceptanceData.push(this.projectContent,  this.advanceCharge, this.plusDeduction, this.taxes, this.bond, this.noTaxesTotalSettlement, this.taxesTotalSettlement, this.totalSettlement)
                }
                if(this.acceptanceData.length == 0) {
                    this.acceptanceData.push(this.projectContent,  this.advanceCharge, this.plusDeduction, this.taxes, this.bond, this.noTaxesTotalSettlement, this.taxesTotalSettlement, this.totalSettlement)
                }
            })
        },
        //获取子级的数据
        async getChildrenInfo (thisLevelId) {
            const res = await httpRequest.getProjectSettlementDetailed({ billId: this.billId, parentId: thisLevelId })
            for (const key in res) {
                Object.assign(res[key], { children: [], hasChildren: true, uuid: getUuid() })
                if(res[key].isDetailed == 1) {
                    const targetList = await this.getHistoryData(res[key])
                    //当单位为总额时数量从施工日报带入
                    if(res[key].unit != '总额' && res[key].type == 1) {
                        const targetProjectLog = await this.getListCanSettleQuantity(res[key])
                        // res[key].settlementQuantity = Number(targetProjectLog[0].sumQty) || 0
                        res[key].settlementAmount = parseInt((res[key].settlementQuantity * (res[key].contractPrice || 0)))
                        res[key].currentTotalSettlementQuantity = ((Number(res[key].prevTotalQuantity) || 0) + (Number(res[key].settlementQuantity) || 0)).toFixed(4) * 1
                        res[key].currentTotalSettlementAmount = (Number(res[key].settlementAmount) || 0) + (Number(res[key].prevTotalAmount) || 0)
                        //保存当前可结算施工量
                        res[key].projectLog = Number(targetProjectLog[0].sumQty) || 0
                    }
                    let totalQuantity = 0
                    let totalAmount = 0
                    let max = 0
                    targetList.forEach(item=>{
                        //目标
                        if(item.type == 'target') {
                            totalQuantity = item.totalQuantity || 0
                            totalAmount = item.totalAmount || 0
                            max = item.max
                            const currentTotalSettlementAmount = this.summationResToOrFourDecimal(item.totalAmount, res[key].settlementAmount)
                            const currentTotalSettlementQuantity = this.summationResToOrFourDecimal(item.totalQuantity, res[key].settlementQuantity, 4)
                            Object.assign(res[key], { children: [], hasChildren: false,  prevTotalQuantity: totalQuantity, prevTotalAmount: totalAmount, currentTotalSettlementAmount, currentTotalSettlementQuantity })
                            this.setHistoryPeriods(max)
                        }else {
                            const currentTotalSettlementAmount = this.summationResToOrFourDecimal(item.totalAmount, this.taxes.settlementAmount)
                            //税金
                            Object.assign(this.taxes, { prevTotalAmount: item.totalAmount, currentTotalSettlementAmount, ...item.other })
                            this.setHistoryPeriods(item.max)
                        }

                    })

                }
            }
            return res
        },
        //懒加载数据
        async onload (row, treeNode, resolve) {
            let result = []
            if(row.children.length > 0) {
                result = row.children
            }else{
                if(row.isDetailed != 1) {
                    try {
                        result = await this.getChildrenInfo(row.thisLevelId) //本级id
                    } catch (error) {
                        result = []
                    }
                }
            }
            row.children = result
            if(result.length == 0) {
                row.lowestChild = true
            }
            resolve(result)
        },
        //获取汇总信息（预付款、保证金、加扣款）
        async gethuizongData (contractId, orgId, isAdd) {
            const param = {
                contractId,
                orgId
            }
            const res = await httpRequest.getProjectSettlementTotalList(param)
            let data = []
            if(res && res.length > 0) {
                for (const k in res) {
                    if(res[k].isDetailed == 1) {
                        const targetList = await this.getHistoryData(res[k])
                        let totalQuantity = 0
                        let totalAmount = 0
                        let max = 0
                        targetList.forEach(item=>{
                            //目标
                            if(item.type == 'target') {
                                totalQuantity = item.totalQuantity || 0
                                totalAmount = item.totalAmount || 0
                                max = item.max
                                const currentTotalSettlementAmount = this.summationResToOrFourDecimal(totalAmount, res[k].settlementAmount)
                                const currentTotalSettlementQuantity = this.summationResToOrFourDecimal(totalQuantity, res[k].settlementQuantity, 4)
                                Object.assign(res[k], { children: [], hasChildren: false,  prevTotalQuantity: res[k].type == 3 ? '--' : totalQuantity, prevTotalAmount: totalAmount, currentTotalSettlementAmount, currentTotalSettlementQuantity })
                                this.setHistoryPeriods(max)
                            }else {
                                const currentTotalSettlementAmount = this.summationResToOrFourDecimal(item.totalAmount, this.taxes.settlementAmount)
                                //税金
                                Object.assign(this.taxes, { prevTotalAmount: item.totalAmount, currentTotalSettlementAmount, ...item.other })
                                this.setHistoryPeriods(item.max)
                            }
                        })
                    }
                }
                data = res
            }
            const yufuList = data.filter(item=>item.type == 2)
            const jiakouList = data.filter(item=>item.type == 3)
            const baozhengList = data.filter(item=>item.type == 4)
            const jiakouTree = this.listConversionTreeOther(jiakouList, '0', isAdd)
            this.plusDeduction.children = jiakouTree
            //保证金如果已存在将changeType修改2
            if(this.bond.children.length > 0) {
                const copyList = JSON.parse(JSON.stringify(this.bond.children))
                const bondArr = this.flatTree(copyList)
                bondArr.forEach(item=>{
                    item.settlementAmount = 0
                    item.currentTotalSettlementAmount = 0
                })
                const bondTree = this.listConversionTreeOther(bondArr, '0', 2)
                this.bond.children = bondTree
                //没有则直接赋值
            }else {
                const baozhengTree = this.listConversionTreeOther(baozhengList, '0', isAdd)
                this.bond.children = baozhengTree
            }
            //预付款相同
            if(this.advanceCharge.children.length > 0) {
                const copyList = JSON.parse(JSON.stringify(this.advanceCharge.children))
                const advanceChargeArr = this.flatTree(copyList)
                advanceChargeArr.forEach(item=>{
                    item.settlementAmount = 0
                    item.currentTotalSettlementAmount = 0
                })
                const advanceChargeTree = this.listConversionTreeOther(advanceChargeArr, '0', 2)
                this.advanceCharge.children = advanceChargeTree
            }else {
                const yufuTree = this.listConversionTreeOther(yufuList, '0', isAdd)
                this.advanceCharge.children = yufuTree
            }
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //验证是否至少存在一种结算类型(true不满足,false满足)
        thereIsAtLeastOne () {
            const res = [this.projectContent.children.length, this.advanceCharge.children.length, this.plusDeduction.children.length, this.bond.children.length].some(item=>item > 0)
            //取反方便后续验证
            return !res
        },
        //验证结算类型中的必填项是否为为0(true满足,false不满足)
        isAreTheyAllZero () {
            //合同内容
            let isHeTong = true
            let isYufukuan = true
            let isBaozhengjin = true
            if(this.projectContent.children.length > 0) {
                const cloneList = JSON.parse(JSON.stringify(this.projectContent.children))
                const arrList = this.flatTree(cloneList)
                isHeTong = arrList.every(item=>{
                    if(item.isDetailed == 1) {
                        //判断是金额必填还是数量必填
                        const target = item.unit == '总额' ? item.settleAmount : item.settlementQuantity
                        return Number(target) == 0
                    } else {
                        return true
                    }
                })
            }

            //预付款
            if(this.advanceCharge.children.length > 0) {
                isYufukuan = this.advanceCharge.children.every(son=>son.settlementAmount == 0)
            }

            //保证金
            if(this.bond.children.length > 0) {
                this.bond.children && this.bond.children.forEach(item=>{
                    if(item.children && item.children.length > 0) {
                        //1扣 2返
                        isBaozhengjin = item.children.every(son=>son.settlementAmount == 0)
                    }
                })
            }

            const res = [isHeTong, isYufukuan, isBaozhengjin].every(i=>i)
            return res
        },
        //选择合同后根据乙方id获取对应外包方信息
        async getSecondPartyData (id) {
            const [data] =  await httpRequest.getSecondPartyData({
                'keyword': '',
                'listid': [id]
            })
            if(data) {
                //如果外包方验证码有误后端会直接抛出异常不需要前端进行判断
                const res = await httpRequest.getSecondPartyState({ code: data.creditCode })
                //此验证接口只以状态(code)==200为成功其他都是失败
                if(typeof res == 'object') {
                    if(res.code && res.code == 200) {
                        return false
                    }else {
                        return true
                    }
                //接口封装逻辑为如果只返回data说明code==200
                }else {
                    return false
                }
            } else {
                return false
            }
        },
        //弹窗选择清单结算明细
        settleOrgChange (contractId) {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: 'SelectProjectSettleDetail', //调动单和物资弹框
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify(contractId),
                // InitParamsStr: contractId,
                Title: '引入清单' // 标题
            }).then(async res=>{
                // this.setSelectedInfo(res)
                // openAppClient('/showSelectedData', '选择结果')
                let isSon = [] //用于找到并接受最子级细目的结构部分
                res.forEach(item=>{
                    //找到最子级细目并筛选出来
                    if(item.Structure && item.Structure.length > 0) {
                        item.Structure.forEach(line=>{
                            line.thisLevelId = line.listId
                            line.structureName = line.structureNamePaths
                            line.unit = item.unit
                            //最子级细目保存父级id用于后续赋值sourceId
                            line.isFather = line.parentId
                        })
                        isSon.push(...item.Structure)
                    }
                    item.thisLevelId = item.listId
                })
                res.push(...isSon)
                //将当前树转换为一维数组
                let resList = res //默认等于接口查询数据
                //当存在老数据时保存老数据处理新数据
                if(this.projectContent.children.length > 0) {
                    const cloneList = JSON.parse(JSON.stringify(this.projectContent.children))
                    const arrList = this.flatTree(cloneList)
                    arrList.forEach(item=>{
                        //更新表格一定要更新row-key不然表格不会刷新！！
                        item.uuid = getUuid()
                    })
                    resList = this.duplicateRemoval(arrList, res)
                }
                const resTree = this.listConversionTree(resList, '0')
                const cloneList = JSON.parse(JSON.stringify(resTree))
                const returnList = this.flatTree(cloneList)
                for (const k in returnList) {
                    if(returnList[k].isDetailed == 1) {
                        const targetList = await this.getHistoryData(returnList[k])
                        //当单位为总额时数量从施工日报带入
                        if(returnList[k].unit != '总额' ) {
                            const targetProjectLog = await this.getListCanSettleQuantity(returnList[k])
                            returnList[k].settlementQuantity = Number(targetProjectLog[0].sumQty) || 0
                            returnList[k].settlementAmount = parseInt((returnList[k].settlementQuantity * (returnList[k].contractPrice || 0)))
                            returnList[k].currentTotalSettlementQuantity = ((Number(returnList[k].prevTotalQuantity) || 0) + (Number(returnList[k].settlementQuantity) || 0)).toFixed(4) * 1
                            returnList[k].currentTotalSettlementAmount = (Number(returnList[k].settlementAmount) || 0) + (Number(returnList[k].prevTotalAmount) || 0)
                            //保存当前可结算施工量
                            returnList[k].projectLog = Number(targetProjectLog[0].sumQty) || 0
                        }
                        let totalQuantity = 0
                        let totalAmount = 0
                        let max = 0
                        targetList.forEach(item=>{
                            //目标
                            if(item.type == 'target') {
                                totalQuantity = item.totalQuantity || 0
                                totalAmount = item.totalAmount || 0
                                max = item.max
                                const currentTotalSettlementAmount = this.summationResToOrFourDecimal(item.totalAmount, returnList[k].settlementAmount)
                                const currentTotalSettlementQuantity = this.summationResToOrFourDecimal(item.totalQuantity, returnList[k].settlementQuantity, 4)
                                Object.assign(returnList[k], { children: [], hasChildren: false,  prevTotalQuantity: totalQuantity, prevTotalAmount: totalAmount, currentTotalSettlementAmount, currentTotalSettlementQuantity })
                                this.setHistoryPeriods(max)
                            }else {
                                const currentTotalSettlementAmount = this.summationResToOrFourDecimal(item.totalAmount, this.taxes.settlementAmount)
                                //税金
                                Object.assign(this.taxes, { prevTotalAmount: item.totalAmount, currentTotalSettlementAmount, ...item.other })
                                this.setHistoryPeriods(item.max)
                            }
                        })
                    }
                }
                const treeList = this.listConversionTree(returnList, '0')
                this.projectContent.children = treeList
            })
        },
        //合同工程内容逐一遍历并新增没有的细目
        duplicateRemoval (oldList = [], newList = []) {
            //旧数据
            for (let i = 0; i < oldList.length; i++) {
                //新数据
                for (let j = 0; j < newList.length; j++) {
                    if(oldList[i].thisLevelId == newList[j].thisLevelId) {
                        newList.splice(j, 1)
                        j--
                        break
                    }
                }
            }
            return [...oldList, ...newList]
        },
        //设置合同清单子级数据
        setSonData (old) {
            if(old.isDetailed !== undefined) {
                return { ...old }
            }
            const { billId } = this.formData
            const itemObj = {
                billId, //其他结算id
                changeType: 1, // 变更类型
                contractAmount: old.amount, // 合同金额
                contractPrice: old.unitPrice, //合同单价
                contractQuantity: old.quantity, //合同数量
                currentTotalSettlementAmount: old.currentTotalSettlementAmount || 0, //截止本期末累计结算金额
                currentTotalSettlementQuantity: old.currentTotalSettlementQuantity || 0, //截止本期末累计结算数量
                dtlId: '', //其他结算清单id
                isBillLevel: 0, //是否为单据层(加扣款清单,0:否;1:是)
                isDetailed: 0, //是否最子级 0不是 1 是
                itemName: old.itemName, //细目名称
                itemNo: old.itemNo, //细目编号
                // marginType:保证金类型(1:扣;2:返)
                parentId: old.parentId, //父级id
                thisLevelId: old.listId, //本级id
                settlementAmount: old.settlementAmount || 0, //本期结算金额
                settlementQuantity: old.settlementQuantity || 0, //本期结算数量
                sourceId: old.isFather || old.listId, //源单明细id
                structureId: old.structureId || '', //结构部位清单id
                structureName: old.structureName || '', //结构部位清单名称
                type: 1, //结算清单类型(1:清单;3:加扣款;4:保证金)
                unit: old.unit, //单位
                uuid: getUuid(), //表格需要的id
                projectLog: old.projectLog || ''
            }
            return itemObj
        },
        //将合同清单数据转为需要的树
        listConversionTree (arr, parentId) {
            const tree = []
            let temp
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].parentId == parentId) {
                    const getObj = this.setSonData(arr[i])
                    const obj = getObj
                    temp = this.listConversionTree(arr, arr[i].thisLevelId)
                    if (temp.length > 0) {
                        obj.children = temp
                        obj.hasChildren = true
                    } else {
                        obj.isDetailed = 1 //最子级（树的最底层）为1
                        obj.children = []
                        obj.hasChildren = false
                        obj.lowestChild = true
                    }
                    tree.push(obj)
                }
            }
            return tree
        },
        //将预付款、加扣款、保证金转为需要的树
        listConversionTreeOther (arr, parentId, isAdd) {
            const tree = []
            let temp
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].parentId == parentId) {
                    arr[i].uuid = getUuid()
                    const obj = arr[i]
                    temp = this.listConversionTreeOther(arr, arr[i].thisLevelId, isAdd)
                    if (temp.length > 0) {
                        obj.children = temp
                        obj.changeType = isAdd
                    } else {
                        obj.changeType = isAdd
                        obj.children = []
                        obj.lowestChild = true
                        obj.settlementAmount = obj.settlementAmount || 0
                        obj.prevTotalAmount = obj.prevTotalAmount || 0
                        obj.currentTotalSettlementAmount = obj.currentTotalSettlementAmount || 0
                        //预付款与保证金展示为比例
                        if(obj.type == 4 || obj.type == 2) {
                            const contractAmount = obj.contractAmount
                            obj.prevTotalQuantity = contractAmount ? (obj.prevTotalAmount / contractAmount * 100).toFixed(4) * 1 : 0
                            const quantity = (obj.currentTotalSettlementAmount / contractAmount * 100).toFixed(4) * 1
                            obj.currentTotalSettlementQuantity = contractAmount ? (quantity + obj.prevTotalQuantity).toFixed(4) * 1 : 0

                        }
                    }
                    tree.push(obj)
                }
            }
            return tree
        },
        //获取目标下的所有子级转为后端需要的参数
        getChildrenList (row) {
            const copyList = JSON.parse(JSON.stringify(row))
            const paramList = this.flatTree([copyList])
            return paramList
        },
        //在树中找到目标并删除
        seekTreeDeleteTarget (list, sourceId) {
            for (let i = 0; i < list.length; i++) {
                if(list[i].sourceId == sourceId) {
                    list.splice(i, 1)
                    return
                }else {
                    list[i].children && this.seekTreeDeleteTarget(list[i].children, sourceId)
                }
            }
        },
        //删除树中的空父级
        deleteNoChildrenFather (list) {
            list
        },
        //删除单条结算明细数据 tps
        handleDeletePlanList (row) {
            this.clientPop(
                'info',
                '是否删除本级及下级数据？',
                ()=>{
                    //合同工程内容
                    if(row.type == 1) {
                        //获取目标以及目标下面所有子级并验证是否传给后端
                        const targetAndChildren = this.getChildrenList(row)
                        //在树中删除目标
                        this.seekTreeDeleteTarget(this.projectContent.children, row.sourceId)
                        //是否需要发送接口
                        targetAndChildren.forEach(item=>{
                            if(item.changeType != 1) {
                                item.changeType = -1
                            }
                        })
                        //不需要删除子级,后端会判断并删除
                        const parmesList = targetAndChildren.filter(item=>item.changeType == -1)
                        if(parmesList.length > 0) {
                            httpRequest.updeteProjectSettlementDetailed(parmesList)
                        }
                    }
                    else {
                        this.plusDeduction.children[0].children.forEach((item, index)=>{
                            if(item.itemName == row.itemName) {
                                //如果当前选中的是新增数据只需要把从数组中删除即可
                                if(row.changeType != 1) {
                                    //如果父级下面只有这一条那么把父级一起删除
                                    let copyList = []
                                    let paramList = []
                                    if(this.plusDeduction.children.length == 1) {
                                        copyList = JSON.parse(JSON.stringify(this.plusDeduction.children))
                                        paramList = this.flatTree(copyList)
                                    }else {
                                        copyList = JSON.parse(JSON.stringify(this.plusDeduction.children[0].children[index]))
                                        paramList = this.flatTree([copyList])
                                    }
                                    paramList.forEach(item=>{
                                        if(item.changeType != 1) {
                                            item.changeType = -1
                                            item.billId = this.billId
                                        }
                                    })
                                    httpRequest.updeteProjectSettlementDetailed(paramList)
                                }
                                //删除同理
                                if(this.plusDeduction.children[0].children.length == 1) {
                                    this.plusDeduction.children.splice(0, 1)
                                }else {
                                    this.plusDeduction.children[0].children.splice(index, 1)
                                }
                                if(this.plusDeduction.children.length == 0) {
                                    this.plusDeduction = {
                                        ...this.plusDeduction,
                                        settlementAmount: 0, //本期结算金额
                                        settlementQuantity: 0, //本期结算金额
                                        prevTotalAmount: 0, //截止上期末累计结算金额
                                        currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                                    }
                                }
                            }
                        })
                    }
                }
            )
        },
        //将树处理为后端需要的一维数组
        flatTree (tree, list = []) {
            tree.forEach(item=>{
                const children = item.children
                delete item.children
                list.push(item)
                children && this.flatTree(children, list)
            })
            return list
        },
        //跳转至加扣款结算页面
        examine (row) {
            const billId = row.dtlId
            openAppClient(
                `/guochengJkkJieshuanView?isview=true&billid=${billId}`, '查看加扣款结算'
            )
        },
        //操作成功后返回列表页面
        printHandel () {
            this.$router.replace('/guochengZqJieshuanList')
        },
        //设置合计
        setTotalSettlement (list, target) {
            target['settlementAmount'] = list.reduce((a, b)=>a + (Number(b.settlementAmount) || 0), 0).toFixed(2) * 1
            target['prevTotalAmount'] = list.reduce((a, b)=>a + (Number(b.prevTotalAmount) || 0), 0).toFixed(2) * 1
            target['currentTotalSettlementAmount'] = list.reduce((a, b)=>a + (Number(b.currentTotalSettlementAmount) || 0), 0).toFixed(2) * 1
            // let i = 1
            // let isWhile = true
            // while (isWhile) {
            //     if(list[0]['settleAmount' + i]) {
            //         obj['settleAmount' + i] = list.reduce((a, b)=>a + (Number(b['settleAmount' + i] ) || 0), 0).toFixed(2) * 1
            //     }else {
            //         isWhile = false
            //     }
            // }
        },
        //表格搜索
        searchTableData () {
            if(this.formData.contractId) {
                httpRequest.searchDetailedList({ key: this.searchVal, sourceId: this.formData.contractId })
                    .then(res=>{
                        const tree = this.searchDataOrTree(res, '0')
                        this.acceptanceData[0].children = tree
                    })
            }
        },
        //将搜索出来的清单转为树（搜索与弹框与结算所用参数不统一）
        searchDataOrTree (arr, parentId) {
            const tree = []
            let temp
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].parentId == parentId) {
                    const getObj = this.setSearchParmes(arr[i])
                    const obj = getObj
                    temp = this.searchDataOrTree(arr, arr[i].oriBillId)
                    if (temp.length > 0) {
                        obj.children = temp
                        obj.hasChildren = true
                    } else {
                        obj.isDetailed = 1 //最子级（树的最底层）为1
                        obj.children = []
                        obj.hasChildren = false
                        obj.lowestChild = true
                    }
                    tree.push(obj)
                }
            }
            return tree
        },
        //设置搜索出来的参数转为工程需要的参数
        setSearchParmes (old) {
            const { billId } = this.formData
            const itemObj = {
                billId, //其他结算id
                changeType: 1, // 变更类型
                contractAmount: old.amount, // 合同金额
                contractPrice: old.unitPrice, //合同单价
                contractQuantity: old.quantity, //合同数量
                currentTotalSettlementAmount: 0, //截止本期末累计结算金额
                currentTotalSettlementQuantity: 0, //截止本期末累计结算数量
                dtlId: '', //其他结算清单id
                isBillLevel: 0, //是否为单据层(加扣款清单,0:否;1:是)
                isDetailed: 0, //是否最子级 0不是 1 是
                itemName: old.itemName, //细目名称
                itemNo: old.itemNo, //细目编号
                // marginType:保证金类型(1:扣;2:返)
                parentId: old.parentId, //父级id
                thisLevelId: old.oriBillId, //本级id
                settlementAmount: 0, //本期结算金额
                settlementQuantity: 0, //本期结算数量
                sourceId: old.oriBillId, //源单明细id sourceId
                structureId: old.oriBillId, //结构清单id
                structureName: old.structureName, //结构名称
                type: 1, //结算清单类型(1:清单;3:加扣款;4:保证金)
                unit: old.unit, //单位
                uuid: getUuid(), //表格需要的id
            }
            return itemObj
        },
        //可执行删除操作的行 tps
        isOnDelete (row) {
            //合同工程内容每一层都可以删除
            if(row.type == 1 && !row.serialNumber) {
                return true
            }
            //加扣款只能删除工程加扣款和其他加扣款
            if(row.type == 3) {
                if(row.itemName == '工程加扣款' || row.itemName == '其他加扣款') {
                    return true
                }else {
                    return false
                }
            }
            return false
        },
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.el-tab-pane {
    margin-left: -10px;
}

.form {
    margin-top: 10px;
}

.bigBox {
    padding: 0 10px;
    .top {
        margin: 0 auto;
        background: #fff;
        display: flex;
        justify-content: space-between;
        padding: 10px;
        margin-bottom: 20px;
        border-radius: 5px;
        box-shadow: 1px 1px 5px rgba(201, 198, 198, 0.804);
        .right {
            margin-left: 20px;
        }
    }
}

.goTo {
    color: blue;
    cursor: pointer;
    font-size: 12px;
}

.e-table {
    background: #fff;
}
.handle {
    margin-top: 10px;
}
.errMessage {
    color: red;
    font-size: 14px;
}

.select_box {
    display: flex;
    align-items: center;
    .label {
        margin: 0 0 0 10px;
        font-weight: bold;
        font-size: 13px;
    }
    ::v-deep .el-radio-group {
        display: flex;
        .el-radio {
            display: flex;
            align-items: center;
            margin-right: 10px;
        }
    }
}

.account_item_clear {
    ::v-deep .el-select {
        .el-select__tags {
            .el-tag {
                .el-tag__close {
                    display: none;
                }
            }
        }
    }
}
</style>
